import { ipcMain, BrowserWindow } from 'electron';
import { execFile } from 'child_process';
import path from 'path';
import os from 'os';
// 确保只注册一次
export function registerSystemHandlers() {
  ipcMain.handle('system:getComputerName', () => {
    return os.hostname();
  });

  // 获取系统当前可用的打印机列表
  ipcMain.handle('system:getPrinters', async () => {
    try {
      const win = BrowserWindow.getAllWindows()[0];
      if (!win) return [];
      const wc: any = win.webContents as any;
      if (typeof wc.getPrintersAsync === 'function') {
        return await wc.getPrintersAsync();
      }
      return wc.getPrinters();
    } catch (e) {
      return [];
    }
  });

  // 获取当前在线的打印机列表（Windows 使用 PowerShell 精准判断） 暂时无效 没法判断是不是就绪的
  ipcMain.handle('system:getOnlinePrinters', async () => {
    try {
      if (process.platform === 'win32') {
        const psCommand = "Get-Printer | Select-Object Name,WorkOffline,PrinterStatus,PortName,Shared,Published | ConvertTo-Json -Compress";
        const result = await new Promise<any[]>((resolve) => {
          execFile('powershell.exe', ['-NoProfile', '-Command', psCommand], { windowsHide: true }, (err, stdout) => {
            if (err) {
              resolve([]);
              return;
            }
            try {
              const json = JSON.parse(stdout || '[]');
              const arr = Array.isArray(json) ? json : (json ? [json] : []);
              resolve(arr);
            } catch {
              resolve([]);
            }
          });
        });
        console.log('获取打印机列表:', result);


        // 规则：不离线(WorkOffline=false) 且 打印机状态空/0/3(Idle)
        const online = result.filter((p: any) => {
          const wo = p?.WorkOffline === false;
          const status = typeof p?.PrinterStatus === 'number' ? p.PrinterStatus : -1;
          const okStatus = [0, 3, null, undefined].includes(status);
          return wo && okStatus;
        });
        return online.map((p: any) => ({
          name: p?.Name,
          isDefault: false,
          isOnline: true,
          status: p?.PrinterStatus,
          portName: p?.PortName
        }));
      }

      // 其他平台回退到 Chromium 提供的列表
      const win = BrowserWindow.getAllWindows()[0];
      if (!win) return [];
      const wc: any = win.webContents as any;
      const printers = typeof wc.getPrintersAsync === 'function' ? await wc.getPrintersAsync() : wc.getPrinters();
      return printers;
    } catch {
      return [];
    }
  });

  // 全局打印窗口管理
  const printWindows: { [key: string]: any } = {};

  const PRINT_TIMEOUT_MS = 15000;
  let currentPrintWindow: BrowserWindow | null = null;
  let currentPrintResolve: ((value: any) => void) | null = null;
  let currentPrintWatchdog: NodeJS.Timeout | null = null;

  const clearPrintWatchdog = () => {
    if (currentPrintWatchdog) {
      clearTimeout(currentPrintWatchdog);
      currentPrintWatchdog = null;
    }
  };

  const resetPrintContext = () => {
    clearPrintWatchdog();
    currentPrintWindow = null;
    currentPrintResolve = null;
  };

  const startPrintWatchdog = (message: string) => {
    clearPrintWatchdog();
    currentPrintWatchdog = setTimeout(() => {
      console.error('打印流程超时:', message);
      currentPrintResolve?.({
        success: false,
        failureReason: 'timeout',
        errorMessage: message
      });
      currentPrintWindow?.close();
      resetPrintContext();
    }, PRINT_TIMEOUT_MS);
  };


  // 打印处理 - 使用HTML模板 + 单窗口复用
  ipcMain.handle('printStart', async (event, printerName: string, data: any, pageType: string) => {
    try {
      console.log('收到打印请求:', { printerName, pageType, data });

      const win = BrowserWindow.getAllWindows()[0];
      if (!win) {
        throw new Error('主窗口不存在');
      }

      // 每次都创建新的打印窗口（和老项目保持一致）
      const printWindow = new BrowserWindow({
        webPreferences: {
          contextIsolation: false,
          nodeIntegration: true,
          // enableRemoteModule: true
        },
        show: false, // 默认隐藏窗口，避免GPU渲染问题，调试时可以打开true
        width: 800,  // 标准宽度
        height: 600  // 标准高度，避免过大导致GPU问题
      });

      // 直接加载对应的HTML模板文件（从public目录）
      const htmlPath = path.join(process.env.VITE_PUBLIC, pageType)
      console.log('加载HTML模板:', htmlPath);
      await printWindow.loadURL(htmlPath);

      return new Promise((resolve, reject) => {
        // 设置全局引用，供回调使用
        currentPrintWindow = printWindow;
        currentPrintResolve = resolve;
        printWindow.on('closed', () => {
          resetPrintContext();
        });
        printWindow.webContents.once('did-stop-loading', () => {
          console.log('HTML模板停止加载');

          // 使用did-stop-loading事件来触发打印流程
          setTimeout(() => {
            console.log('HTML模板加载完成（使用did-stop-loading）');
            try {
              // 发送数据到HTML模板
              console.log('发送数据到HTML模板');
              printWindow.webContents.send('print-info',
                printerName,
                data,
                pageType
              );
              startPrintWatchdog('未收到HTML模板触发打印事件，已自动关闭打印窗口');
              // 不在这里打印，等待HTML模板发送'do'事件来触发打印
            } catch (error) {
              console.error('打印过程出错:', error);
              printWindow.close();
              resetPrintContext();
              reject({ success: false, failureReason: error });
            }
          }, 500); // 给HTML模板一些时间处理数据
        });
      });

    } catch (error) {
      console.error('打印任务失败:', error);
      return { success: false, message: '打印任务失败' };
    }
  });

  // 处理HTML模板发送的打印请求
  ipcMain.on('printStart', (event, printerName, contentHeight) => {
    console.log('收到HTML模板的打印请求:', printerName, '内容高度:', contentHeight);

    if (currentPrintWindow && currentPrintResolve) {
      clearPrintWatchdog();
      // 根据内容高度计算打印高度
      // 为了确保不被分页，使用更保守的计算方式
      // 直接使用像素值 * 800微米，确保有足够空间
      const calculatedHeight = contentHeight * 800;

      console.log('开始打印，打印机:', printerName, '页面尺寸:', {
        width: 72100,
        height: calculatedHeight,
        contentHeight: contentHeight
      });

      currentPrintWindow.webContents.print({
        silent: true,
        printBackground: false,
        deviceName: printerName,
        pageSize: {
          width: 72100,   // 72.1mm宽度（实际可打印宽度）
          height: calculatedHeight  // 根据内容高度动态计算
        },
        margins: {
          marginType: 'none'
        }
      }, (success: boolean, failureReason: string) => {
        console.log('打印结果:', { success, failureReason, printerName });
        
        // 处理打印错误
        if (!success) {
          console.error('打印失败:', failureReason);
          
          // 根据错误类型提供具体建议
          let errorMessage = '打印失败';
          if (failureReason.includes('0x80040003')) {
            errorMessage = '打印机配置异常，请检查打印机驱动和连接状态';
          } else if (failureReason.includes('offline')) {
            errorMessage = '打印机离线，请检查打印机连接';
          } else if (failureReason.includes('not found')) {
            errorMessage = '未找到指定打印机，请检查打印机名称';
          }
          
          console.error('打印错误详情:', errorMessage);
        }
        
        // 关闭打印窗口
        currentPrintWindow?.close();
        currentPrintResolve?.({ 
          success, 
          failureReason,
          errorMessage: success ? null : (failureReason.includes('0x80040003') ? '打印机配置异常，请检查打印机驱动和连接状态' : failureReason)
        });
        // 清理引用
        resetPrintContext();
      });
    } else {
      console.error('打印窗口或resolve函数不存在');
    }
  });

}
